{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f0cdc456",
   "metadata": {},
   "source": [
    "# Week15_函数与模块进阶"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8cb76c50",
   "metadata": {},
   "source": [
    "--------\n",
    "* 记录人：liuqt    \n",
    "* 时间：2021-12-06   \n",
    "* week15   \n",
    "* 主要参考文档:\n",
    "> 1. [Python官方文档](https://python.org/doc)\n",
    "> 2. [博客--函数](https://www.cnblogs.com/xuzhichao/p/11570285.html)\n",
    "\n",
    "--------"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76195713",
   "metadata": {},
   "source": [
    "## 上周回顾\n",
    "> 1. 函数的定义： def\n",
    "> 2. 函数名的定义规则-->变量名一样的规则\n",
    "> 3. 调用函数的方式\n",
    "> 4. 参数:\n",
    ">> 1. 形式参数(定义参数)\n",
    ">> 2. 实际参数(调用函数)\n",
    ">> 3. 有多个参数时：\n",
    ">>> 1. 关键字参数\n",
    ">>> 2. 位置参数（调用函数时）-->关键字参数要均放在末尾（多个考虑顺序）\n",
    ">>> 3. 默认参数（定义函数时）-->默认参数均放在末尾（多个不考虑顺序）\n",
    "\n",
    "## 本周知识\n",
    "\n",
    "> 1. 函数的返回值\n",
    "> 2. 函数的参数类型\n",
    "> 3. 模块与函数的关系\n",
    "> 4. 定义一个模块，然后调用模块\n",
    ">> 1. 调用模块\n",
    ">> 2. 调用模块中的函数\n",
    "> 5. 模块与函数实践\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2b49c04",
   "metadata": {},
   "source": [
    "## 1. 函数的返回值\n",
    "\n",
    "> 1. 函数一定有返回值（无论是什么编程语言）\n",
    "> 2. 在其他的编程语言中（如C语言，java等），返回值一定要写，不写会报错！；对于python（更高级的语言），返回值如果不写，给定默认值 None\n",
    "> 3. 返回值一般为函数体运行的结果（result），也可以是自定义的函数返回值(实践2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "2a96b888",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 函数返回值实践1\n",
    "def get_formatted_name(first_name,last_name):\n",
    "    \"\"\"返回整洁的姓名\"\"\"\n",
    "    full_name = first_name + ' ' + last_name\n",
    "#     print(full_name)\n",
    "    return full_name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "8d89849f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Li Hua\n"
     ]
    }
   ],
   "source": [
    "print(get_formatted_name(\"Li\",\"Hua\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "f5c3a253",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 函数返回值实践2\n",
    "def log_in(username,password):\n",
    "    \"\"\"验证登录信息\"\"\"\n",
    "    if username == \"Lihua\" and password == 123456:\n",
    "        return 1\n",
    "    else:\n",
    "        return 2 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "c0c6f219",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "log_in(\"LiHua\",123456)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "118836ee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "log_in(\"Lihua\",123456)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e825915",
   "metadata": {},
   "source": [
    "## 2.函数的参数\n",
    "\n",
    "### 1.函数输入的参数\n",
    "> 1. 函数可以输入复杂的函数：\n",
    ">> 1. 函数参数为列表\n",
    ">> 2. 函数参数为字典\n",
    "> 2. 函数可以输入不确定个数的参数：\n",
    ">> 1. *args\n",
    ">> 2. **kwarges"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "331b312a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def list_test(names):\n",
    "    \"\"\"测试输入参数为列表\"\"\"\n",
    "    print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "eb22af3e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['lihua', 'xiaohong', 'xiaoming']\n"
     ]
    }
   ],
   "source": [
    "list_test([\"lihua\",\"xiaohong\",\"xiaoming\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "9976f814",
   "metadata": {},
   "outputs": [],
   "source": [
    "def dict_test(request_header):\n",
    "    \"\"\"测试输入参数为字典\"\"\"\n",
    "    print(request_header)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "246546d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://httpbin.org/get\n",
    "httpbin_get = {\n",
    "  \"args\": {}, \n",
    "  \"headers\": {\n",
    "    \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\", \n",
    "    \"Accept-Encoding\": \"gzip, deflate\", \n",
    "    \"Accept-Language\": \"zh-CN,zh;q=0.9\", \n",
    "    \"Host\": \"httpbin.org\", \n",
    "    \"Upgrade-Insecure-Requests\": \"1\", \n",
    "    \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36\", \n",
    "    \"X-Amzn-Trace-Id\": \"Root=1-61adbb17-5a300ddc133697c750ab0fe3\"\n",
    "  }, \n",
    "  \"origin\": \"61.242.54.43\", \n",
    "  \"url\": \"http://httpbin.org/get\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "fd07affe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Host': 'httpbin.org', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36', 'X-Amzn-Trace-Id': 'Root=1-61adbb17-5a300ddc133697c750ab0fe3'}\n"
     ]
    }
   ],
   "source": [
    "dict_test(httpbin_get['headers'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71973398",
   "metadata": {},
   "source": [
    "> 2. 函数可以输入不确定个数的参数：\n",
    ">> 1. *args\n",
    ">>> 1. args 可以接受多个数据（单值）\n",
    ">>> 2. args 将多个数据存在一个**元组**当中，实际还是一个变量\n",
    ">> 2. **kwargs\n",
    ">>> 1. kwargs 可以接受多个数据（键值对）==> 关键字参数\n",
    ">>> 2. kwargs 将多个键值对的数据存放在一个 **字典** 中，实际上还是一个变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "a5ae58bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def food_ingred(food,*ingreds):\n",
    "    \"\"\"食物配料单\"\"\"\n",
    "    return food,ingreds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "7e8f5a0f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('pizza', ('mushroom', 'green peppes', 'extra cheese'))"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "food_ingred(\"pizza\",\"mushroom\",\"green peppes\",\"extra cheese\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "39248fb5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# **kwargs\n",
    "def person(stu_name,**stu_info):\n",
    "    \"\"\"学生个人信息完善\"\"\"\n",
    "    return stu_name,stu_info"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "1478b678",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('Lihua', {'age': 18, 'job': 'student', 'address': '广州南方学院'})"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "person(\"Lihua\",age=18,job=\"student\",address = \"广州南方学院\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "feed3e69",
   "metadata": {},
   "outputs": [],
   "source": [
    "def func_name(arg1,arg2,*arg,**kwargs):\n",
    "    \"\"\"考虑比较周到的函数参数\"\"\"\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "153e8199",
   "metadata": {},
   "source": [
    "### 2.函数输出的返回值\n",
    "\n",
    "> 1. 返回值可以是 字符串、数值、列表、字典等数据（单一值）\n",
    "> 2. 返回值是唯一的，不可以有两个（这是其他语言，如C语言，Java等）。\n",
    "> 3. python可以输出多个返回值，结果会用一个元组进行封装并返回。（本质不违背函数的定义）==>本质上还是唯一的返回值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "19acd906",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test1_return():\n",
    "    \"\"\"测试返回值return\"\"\"\n",
    "    return \"你好\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "013e57e8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好'"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test1_return()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "ff9c01ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test2_return():\n",
    "    \"\"\"测试返回值return\"\"\"\n",
    "    return 0\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "2f55fd78",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test2_return()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "f0a098dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test3_return():\n",
    "    \"\"\"测试返回值return\"\"\"\n",
    "    return [1,2,3,4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "6d46b6fa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4]"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test3_return()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "d19ea43b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test4_return():\n",
    "    \"\"\"测试返回值return\"\"\"\n",
    "    return {\"stu_2001\":\"xiaohong\",\n",
    "            \"stu_2002\" : \"xiaoming\",\n",
    "            \"stu_2003\" : \"xiaoli\"\n",
    "           }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "e8c117f9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'stu_2001': 'xiaohong', 'stu_2002': 'xiaoming', 'stu_2003': 'xiaoli'}"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test4_return()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "442a182b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def test5_return():\n",
    "    \"\"\"测试返回值return\"\"\"\n",
    "    return httpbin_get['headers']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "2addb790",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n",
       " 'Accept-Encoding': 'gzip, deflate',\n",
       " 'Accept-Language': 'zh-CN,zh;q=0.9',\n",
       " 'Host': 'httpbin.org',\n",
       " 'Upgrade-Insecure-Requests': '1',\n",
       " 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',\n",
       " 'X-Amzn-Trace-Id': 'Root=1-61adbb17-5a300ddc133697c750ab0fe3'}"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test5_return()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "4f35739a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 测试多个值\n",
    "def test6_return():\n",
    "    \"\"\"测试返回值return\"\"\"\n",
    "    return 1,2,\"lihua\",[1,2,3],httpbin_get['headers']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "d4ec2189",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1,\n",
       " 2,\n",
       " 'lihua',\n",
       " [1, 2, 3],\n",
       " {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n",
       "  'Accept-Encoding': 'gzip, deflate',\n",
       "  'Accept-Language': 'zh-CN,zh;q=0.9',\n",
       "  'Host': 'httpbin.org',\n",
       "  'Upgrade-Insecure-Requests': '1',\n",
       "  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',\n",
       "  'X-Amzn-Trace-Id': 'Root=1-61adbb17-5a300ddc133697c750ab0fe3'})"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test6_return()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03de2c76",
   "metadata": {},
   "source": [
    "### 3.模块\n",
    "\n",
    "> 1. 使用模块可以隐藏函数的源代码\n",
    "> 2. 使用的人不需要会底层代码，只需要会使用模块即可\n",
    ">> 1.  必须先调用模块，才可以使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "b5ea2923",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "220849d6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "time.struct_time(tm_year=2021, tm_mon=12, tm_mday=6, tm_hour=16, tm_min=35, tm_sec=21, tm_wday=0, tm_yday=340, tm_isdst=0)"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "time.localtime()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "id": "7ffb8acb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 调用模块中函数的方法一，调用整个模块\n",
    "import study"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "id": "59ceb18e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function search4vowels in module study:\n",
      "\n",
      "search4vowels(word)\n",
      "    计算文本中出现的元音字母有哪些\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(study.search4vowels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "id": "82bc0fdb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a', 'e', 'i', 'o'}"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "study.search4vowels(\"hello this is a python's try\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "id": "9f5bc72c",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "module 'study' has no attribute 'news_link'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-86-90cd1f8bda34>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mhelp\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mstudy\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mnews_link\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: module 'study' has no attribute 'news_link'"
     ]
    }
   ],
   "source": [
    "help(study.news_link)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "5efb1a05",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "module 'study' has no attribute 'news_link'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-85-f21ee4edf2e4>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mstudy\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mnews_link\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'https://www.nfu.edu.cn/'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'xydt'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'96'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: module 'study' has no attribute 'news_link'"
     ]
    }
   ],
   "source": [
    "study.news_link('https://www.nfu.edu.cn/','xydt','96')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "04a59c41",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 调用模块中函数的方法二，调用模块中某一个函数\n",
    "from study import search4vowels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "id": "44fe5859",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'e', 'i'}"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "search4vowels(\"this is my life\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "273a79ac",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
